package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired

    private SetmealDao setmealDao;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        this.setSetmealAndCheckgroup(setmealId,checkgroupIds);

    }
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Setmeal> findAllSet() {
        List<Setmeal> setmealList = setmealDao.queryall();
        return setmealList;
    }

    @Override
    public Setmeal findByid(Integer id) {
        Setmeal setmeal = setmealDao.findByid(id);
        return setmeal;
    }

    @Override
    public Setmeal findonesetmeal(Integer id) {
        Setmeal setmeal = setmealDao.findonesetmeal(id);

        return setmeal;
    }

    @Override
    public Result getsetmeal() {

        List<Map<String, Object>> list = setmealDao.getsetmeal();
        List<String> namelist=new ArrayList<>();
        for (Map<String, Object> map : list) {
            String  name = (String) map.get("name");
            namelist.add(name);
        }
        Map<String ,Object> setmealMap= new HashMap<>();
        setmealMap.put("setmealname",namelist);
        setmealMap.put("setmealcount",list);


        return new Result(true,"",setmealMap);
    }

    public void setSetmealAndCheckgroup(Integer setmealId,Integer[] checkgroupIds){
        if(checkgroupIds != null && checkgroupIds.length > 0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("setmealId",setmealId);
                map.put("checkgroupId",checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }

}
